package liuch.socketdemov2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * socket 服务端，将接收到的client信息发送给所有client端
 */
public class SocketServer {

    private ServerSocket serverSocket;

    private Map<String, PrintWriter> allOut;

    private ExecutorService executorService;

    public SocketServer() {
        try {
            serverSocket = new ServerSocket(8088);

            allOut = new ConcurrentHashMap<>();

            executorService = Executors.newFixedThreadPool(40);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始接受客户端信息
     */
    public void start() {
        while (true) {
            try {
                Socket socket = serverSocket.accept();

                ClientHandler clientHandler = new ClientHandler(socket, allOut);

                executorService.execute(clientHandler);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        SocketServer socketServer = new SocketServer();

        socketServer.start();
    }
}
